// -----------------------------------------------------------------------------
// This source file is part of Matrix Platform
// 	(Universal .NET Software Development Platform)
// For the latest info, see http://www.matrixplatform.com
// 
// Copyright (c) 2009-2010, Ingenious Ltd
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Matrix.Framework.SuperPool.Call;
using Matrix.Framework.SuperPool.DynamicProxy;

namespace Matrix.Framework.SuperPool.Core
{
    /// <summary>
    /// Message super pool class layer, handles incoming proxy type sink callbacks.
    /// </summary>
    public abstract class SuperPoolCallbacks : SuperPoolInvocation, IProxyTypeSink
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        public SuperPoolCallbacks()
        {
            _proxyTypeManager.Sink = this;
        }

        protected abstract void ProcessReceiveEventSubscription(int methodId, Delegate delegateInstance, bool isAdd);

        #region IProxyTypeSink Members

        void IProxyTypeSink.ReceiveMethodCall(int methodId, object[] parameters)
        {
            ProcessReceiveCall(methodId, null, parameters);
        }

        object IProxyTypeSink.ReceiveMethodCallAndReturn(int methodId, Type returnType, object[] parameters)
        {
            return ProcessReceiveCall(methodId, returnType, parameters);
        }

        void IProxyTypeSink.ReceiveEventSubscribed(int methodId, Delegate subscribedDelegate)
        {
            ProcessReceiveEventSubscription(methodId, subscribedDelegate, true);
        }

        void IProxyTypeSink.ReceiveEventUnSubscribed(int methodId, Delegate subscribedDelegate)
        {
            ProcessReceiveEventSubscription(methodId, subscribedDelegate, false);
        }

        object IProxyTypeSink.ReceivePropertyGet(int methodId, Type returnType)
        {
            SuperPoolProxyCall pendingCall = null;
            if (_pendingThreadsCalls.TryGetValue(Thread.CurrentThread.ManagedThreadId, out pendingCall) == false)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find corresponding thread proxy call information.");
#endif
                return null;
            }

            pendingCall.Parameters = null;
            pendingCall.ReturnType = returnType;

            ProxyTypeBuilder builder = ProxyTypeBuilder;
            if (builder == null)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find proxy type builder.");
#endif
                return ProxyTypeManager.GetTypeDefaultValue(returnType);
            }

            pendingCall.MethodInfo = builder.GetMethodInfoById(methodId);
            if (pendingCall.MethodInfo == null)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find method [" + methodId + "] info.");
#endif
                return ProxyTypeManager.GetTypeDefaultValue(returnType);
            }

            return pendingCall.Sender.ProcessCall(pendingCall);
        }

        void IProxyTypeSink.ReceivePropertySet(int methodId, object value)
        {
            SuperPoolProxyCall pendingCall = null;
            if (_pendingThreadsCalls.TryGetValue(Thread.CurrentThread.ManagedThreadId, out pendingCall) == false)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find corresponding thread proxy call information.");
#endif
                return;
            }

            pendingCall.Parameters = new object[] { value };
            pendingCall.ReturnType = null;

            ProxyTypeBuilder builder = ProxyTypeBuilder;
            if (builder == null)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find proxy type builder.");
#endif
                return;
            }

            pendingCall.MethodInfo = builder.GetMethodInfoById(methodId);
            if (pendingCall.MethodInfo == null)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find method [" + methodId + "] info.");
#endif
                return;
            }

            pendingCall.Sender.ProcessCall(pendingCall);
        }


        #endregion

        /// <summary>
        /// Process a pool call.
        /// </summary>
        object ProcessReceiveCall(int methodId, Type returnType, object[] parameters)
        {
            SuperPoolProxyCall pendingCall = null;
            if (_pendingThreadsCalls.TryGetValue(Thread.CurrentThread.ManagedThreadId, out pendingCall) == false)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find corresponding thread proxy call information.");
#endif
                return null;
            }

            pendingCall.Parameters = parameters;
            pendingCall.ReturnType = returnType;

            ProxyTypeBuilder builder = ProxyTypeBuilder;
            if (builder == null)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find proxy type builder.");
#endif
                return ProxyTypeManager.GetTypeDefaultValue(returnType);
            }

            pendingCall.MethodInfo = builder.GetMethodInfoById(methodId);
            if (pendingCall.MethodInfo == null)
            {
#if Matrix_Diagnostics
                InstanceMonitor.OperationError("Failed to find method [" + methodId + "] info.");
#endif
                return ProxyTypeManager.GetTypeDefaultValue(returnType);
            }

            return pendingCall.Sender.ProcessCall(pendingCall);
        }

    }
}
